package net.xuzhen97.distributed.transaction.order.service.executor;

import cn.hutool.core.util.IdUtil;
import net.xuzhen97.distributed.transaction.order.dao.Order;
import net.xuzhen97.distributed.transaction.order.dao.OrderRepository;
import net.xuzhen97.distributed.transaction.order.dao.OrderState;
import net.xuzhen97.distributed.transaction.order.service.dto.OrderAddCmd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 创建订单指令执行器
 * @author xuzhen97
 */
@Service
public class OrderAddCmdExe {

    private final OrderRepository orderRepository;

    @Autowired
    public OrderAddCmdExe(OrderRepository orderRepository){
        this.orderRepository = orderRepository;
    }

    public String execute(OrderAddCmd cmd){
        cmd.validate();
        String id = IdUtil.getSnowflakeNextIdStr();

        Order order = new Order();
        order.setId(id);
        order.setNum(id);
        order.setCourseId(cmd.getCourseId());
        order.setUserId(cmd.getUserId());
        order.setState(OrderState.UNPAY.name());

        LocalDateTime now = LocalDateTime.now();
        order.setCreatedBy(cmd.getOpUserId());
        order.setCreatedDate(now);
        order.setLastModifiedBy(cmd.getOpUserId());
        order.setLastModifiedDate(now);
        orderRepository.save(order);
        return id;
    }
}
